package schedulingScheme;

import java.util.ArrayList;
import java.util.List;


public class SensorNode {

    private double x;
    private double y;
    private double r;
    private double battery;//battery in
    private double eElec = 50E-9;
    private double eAmp = 100E-12;
    boolean on;

    public SensorNode(double x, double y, double r, double battery) {
        super();
        this.x = x;
        this.y = y;
        this.r = r;
        this.battery = battery;
    }

    public boolean inRange(POI POI) {
       return inRange(POI.getX(), POI.getY());

    }
    public boolean inRange(double x, double y){
        if ((getX() - x) * (getX() - x) + (getY() - y) * (getY() - y) < r * r) {
            return true;
        }
        return false;
    }

    boolean gridInRange(double x, double y, double length){
        return inRange(x, y) && inRange(x, y -length) && inRange(x - length, y) && inRange(x - length, y - length);
    }

    public double distance(SensorNode s){
        double xTmp = s.getX()-getX();
        double yTmp = s.getY()-getY();
        return Math.pow( xTmp * xTmp + yTmp * yTmp, 0.5);
    }

    public void sendMessage(SensorNode s, int messageLength) throws BatteryExhaustedException{
        if (! isOn())
            throw new IllegalStateException();
        double energyCost = eElec * messageLength + eAmp * messageLength * distance(s) * distance(s);
        if (battery - energyCost > 0) {
            battery -= energyCost;
        } else {
            battery = 0;
            setOn(false);
            throw new BatteryExhaustedException(this);
        }
    }
    
    public void receiveMessage(int messageLength) throws BatteryExhaustedException{
        if (! isOn())
            throw new IllegalStateException();
        double energyCost = eElec * messageLength;
        if (battery - energyCost > 0) {
            battery -= energyCost;
        } else {
            battery = 0;
            setOn(false);
            throw new BatteryExhaustedException(this);
        }
    }



    public double getX() {
        return x;
    }

    public double getY() {
        return y;
    }

    public double getR() {
        return r;
    }

    public double getBattery() {
        return battery;
    }

    public boolean isOn() {
        return on;
    }

    public void setOn(boolean on) {
        if (on && battery <= 0)
            throw new IllegalStateException("battery exhausted");

        this.on = on;
    }



    @Override
    public String toString() {
        return "Sensor: x = " + getX() +", y = " + getY() + ", b = " + getBattery();
    }

}
